package com.strato.annotation.base.v1_0_0.registry;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;

import com.strato.annotation.base.v1_0_0.activator.Activator;

public class AbstractAnnotationDescriptor implements AnnotationDescriptor {

	private List<Annotation> annotations;
	
	@Override
	public List<Annotation> getAnnotations() {
		return annotations;
	}

	public void setAnnotations(List<Annotation> annotations) {
		this.annotations = annotations;
	}

	protected List<Annotation> extractAnnotations(Annotation[] annotations){
		List<Annotation> list=new ArrayList<Annotation>();
		for(Annotation annotation:annotations){
			if(shouldExtract(annotation)){
				list.add(annotation);
			}
		}
		return list;
	}

	private boolean shouldExtract(Annotation annotation) {
		String className=annotation.annotationType().getName();
		if(className.startsWith("com.strato.")){
			return true;
		}
		String packages=Activator.getContext().getProperty("strato.annotation.packages");
		if(packages!=null&&!"".equals(packages.trim())){
			String[] pkgs=packages.split(",");
			for(String pkg:pkgs){
				pkg=pkg.trim();
				if(className.startsWith(pkg)){
					return true;
				}
			}
		}
		return false;
	}

	public Annotation getAnnotation(Class<?> annotationType) {
		if(annotations==null){
			return null;
		}
		for(Annotation a:annotations){
			if(annotationType.equals(a.annotationType())){
				return a;
			}
		}
		return null;
	}
}
